%matplotlib inline
plot_comparison_over_sampling
ref: imbalaced-learn
Compare over-sampling samplers
The following example attends to make a qualitative comparison between the different over-sampling algorithms available in the imbalanced-learn package.
# Authors: Guillaume Lemaitre <g.lemaitre58@gmail.com>
# License: MIT
print(__doc__)
import matplotlib.pyplot as plt
import seaborn as sns
"poster") sns.set_context(
Automatically created module for IPython interactive environment
The following function will be used to create toy dataset. It uses the :func:~sklearn.datasets.make_classification
from scikit-learn but fixing some parameters.
from sklearn.datasets import make_classification
def create_dataset(
=1000,
n_samples=(0.01, 0.01, 0.98),
weights=3,
n_classes=0.8,
class_sep=1,
n_clusters
):return make_classification(
=n_samples,
n_samples=2,
n_features=2,
n_informative=0,
n_redundant=0,
n_repeated=n_classes,
n_classes=n_clusters,
n_clusters_per_class=list(weights),
weights=class_sep,
class_sep=0,
random_state )
The following function will be used to plot the sample space after resampling to illustrate the specificities of an algorithm.
def plot_resampling(X, y, sampler, ax, title=None):
= sampler.fit_resample(X, y)
X_res, y_res 0], X_res[:, 1], c=y_res, alpha=0.8, edgecolor="k")
ax.scatter(X_res[:, if title is None:
= f"Resampling with {sampler.__class__.__name__}"
title
ax.set_title(title)=ax, offset=10) sns.despine(ax
The following function will be used to plot the decision function of a classifier given some data.
import numpy as np
def plot_decision_function(X, y, clf, ax, title=None):
= 0.02
plot_step = X[:, 0].min() - 1, X[:, 0].max() + 1
x_min, x_max = X[:, 1].min() - 1, X[:, 1].max() + 1
y_min, y_max = np.meshgrid(
xx, yy
np.arange(x_min, x_max, plot_step), np.arange(y_min, y_max, plot_step)
)
= clf.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
Z =0.4)
ax.contourf(xx, yy, Z, alpha0], X[:, 1], alpha=0.8, c=y, edgecolor="k")
ax.scatter(X[:, if title is not None:
ax.set_title(title)
Illustration of the influence of the balancing ratio
We will first illustrate the influence of the balancing ratio on some toy data using a logistic regression classifier which is a linear model.
from sklearn.linear_model import LogisticRegression
= LogisticRegression() clf
We will fit and show the decision boundary model to illustrate the impact of dealing with imbalanced classes.
= plt.subplots(nrows=2, ncols=2, figsize=(15, 12))
fig, axs
= (
weights_arr 0.01, 0.01, 0.98),
(0.01, 0.05, 0.94),
(0.2, 0.1, 0.7),
(0.33, 0.33, 0.33),
(
)for ax, weights in zip(axs.ravel(), weights_arr):
= create_dataset(n_samples=300, weights=weights)
X, y
clf.fit(X, y)=f"weight={weights}")
plot_decision_function(X, y, clf, ax, titlef"Decision function of {clf.__class__.__name__}")
fig.suptitle( fig.tight_layout()
Greater is the difference between the number of samples in each class, poorer are the classification results.
Random over-sampling to balance the data set
Random over-sampling can be used to repeat some samples and balance the number of samples between the dataset. It can be seen that with this trivial approach the boundary decision is already less biased toward the majority class. The class :class:~imblearn.over_sampling.RandomOverSampler
implements such of a strategy.
from imblearn.over_sampling import RandomOverSampler
from imblearn.pipeline import make_pipeline
= create_dataset(n_samples=100, weights=(0.05, 0.25, 0.7))
X, y
= plt.subplots(nrows=1, ncols=2, figsize=(15, 7))
fig, axs
clf.fit(X, y)0], title="Without resampling")
plot_decision_function(X, y, clf, axs[
= RandomOverSampler(random_state=0)
sampler = make_pipeline(sampler, clf).fit(X, y)
model 1], f"Using {model[0].__class__.__name__}")
plot_decision_function(X, y, model, axs[
f"Decision function of {clf.__class__.__name__}")
fig.suptitle( fig.tight_layout()
By default, random over-sampling generates a bootstrap. The parameter shrinkage
allows adding a small perturbation to the generated data to generate a smoothed bootstrap instead. The plot below shows the difference between the two data generation strategies.
= plt.subplots(nrows=1, ncols=2, figsize=(15, 7))
fig, axs
=None)
sampler.set_params(shrinkage=axs[0], title="Normal bootstrap")
plot_resampling(X, y, sampler, ax
=0.3)
sampler.set_params(shrinkage=axs[1], title="Smoothed bootstrap")
plot_resampling(X, y, sampler, ax
f"Resampling with {sampler.__class__.__name__}")
fig.suptitle( fig.tight_layout()
It looks like more samples are generated with smoothed bootstrap. This is due to the fact that the samples generated are not superimposing with the original samples.
More advanced over-sampling using ADASYN and SMOTE
Instead of repeating the same samples when over-sampling or perturbating the generated bootstrap samples, one can use some specific heuristic instead. :class:~imblearn.over_sampling.ADASYN
and :class:~imblearn.over_sampling.SMOTE
can be used in this case.
from imblearn import FunctionSampler # to use a idendity sampler
from imblearn.over_sampling import ADASYN, SMOTE
= create_dataset(n_samples=150, weights=(0.1, 0.2, 0.7))
X, y
= plt.subplots(nrows=2, ncols=2, figsize=(15, 15))
fig, axs
= [
samplers
FunctionSampler(),=0),
RandomOverSampler(random_state=0),
SMOTE(random_state=0),
ADASYN(random_state
]
for ax, sampler in zip(axs.ravel(), samplers):
= "Original dataset" if isinstance(sampler, FunctionSampler) else None
title =title)
plot_resampling(X, y, sampler, ax, title fig.tight_layout()
The following plot illustrates the difference between :class:~imblearn.over_sampling.ADASYN
and :class:~imblearn.over_sampling.SMOTE
. :class:~imblearn.over_sampling.ADASYN
will focus on the samples which are difficult to classify with a nearest-neighbors rule while regular :class:~imblearn.over_sampling.SMOTE
will not make any distinction. Therefore, the decision function depending of the algorithm.
= create_dataset(n_samples=150, weights=(0.05, 0.25, 0.7))
X, y
= plt.subplots(nrows=1, ncols=3, figsize=(20, 6))
fig, axs
= {
models "Without sampler": clf,
"ADASYN sampler": make_pipeline(ADASYN(random_state=0), clf),
"SMOTE sampler": make_pipeline(SMOTE(random_state=0), clf),
}
for ax, (title, model) in zip(axs, models.items()):
model.fit(X, y)=ax, title=title)
plot_decision_function(X, y, model, ax
f"Decision function using a {clf.__class__.__name__}")
fig.suptitle( fig.tight_layout()
Due to those sampling particularities, it can give rise to some specific issues as illustrated below.
= create_dataset(n_samples=5000, weights=(0.01, 0.05, 0.94), class_sep=0.8)
X, y
= [SMOTE(random_state=0), ADASYN(random_state=0)]
samplers
= plt.subplots(nrows=2, ncols=2, figsize=(15, 15))
fig, axs for ax, sampler in zip(axs, samplers):
= make_pipeline(sampler, clf).fit(X, y)
model
plot_decision_function(0], title=f"Decision function with {sampler.__class__.__name__}"
X, y, clf, ax[
)1])
plot_resampling(X, y, sampler, ax[
"Particularities of over-sampling with SMOTE and ADASYN")
fig.suptitle( fig.tight_layout()
SMOTE proposes several variants by identifying specific samples to consider during the resampling. The borderline version (:class:~imblearn.over_sampling.BorderlineSMOTE
) will detect which point to select which are in the border between two classes. The SVM version (:class:~imblearn.over_sampling.SVMSMOTE
) will use the support vectors found using an SVM algorithm to create new sample while the KMeans version (:class:~imblearn.over_sampling.KMeansSMOTE
) will make a clustering before to generate samples in each cluster independently depending each cluster density.
from sklearn.cluster import MiniBatchKMeans
from imblearn.over_sampling import SVMSMOTE, BorderlineSMOTE, KMeansSMOTE
= create_dataset(n_samples=5000, weights=(0.01, 0.05, 0.94), class_sep=0.8)
X, y
= plt.subplots(5, 2, figsize=(15, 30))
fig, axs
= [
samplers =0),
SMOTE(random_state=0, kind="borderline-1"),
BorderlineSMOTE(random_state=0, kind="borderline-2"),
BorderlineSMOTE(random_state
KMeansSMOTE(=MiniBatchKMeans(n_init=1, random_state=0), random_state=0
kmeans_estimator
),=0),
SVMSMOTE(random_state
]
for ax, sampler in zip(axs, samplers):
= make_pipeline(sampler, clf).fit(X, y)
model
plot_decision_function(0], title=f"Decision function for {sampler.__class__.__name__}"
X, y, clf, ax[
)1])
plot_resampling(X, y, sampler, ax[
"Decision function and resampling using SMOTE variants")
fig.suptitle( fig.tight_layout()
When dealing with a mixed of continuous and categorical features, :class:~imblearn.over_sampling.SMOTENC
is the only method which can handle this case.
from collections import Counter
from imblearn.over_sampling import SMOTENC
= np.random.RandomState(42)
rng = 50
n_samples # Create a dataset of a mix of numerical and categorical data
= np.empty((n_samples, 3), dtype=object)
X 0] = rng.choice(["A", "B", "C"], size=n_samples).astype(object)
X[:, 1] = rng.randn(n_samples)
X[:, 2] = rng.randint(3, size=n_samples)
X[:, = np.array([0] * 20 + [1] * 30)
y
print("The original imbalanced dataset")
print(sorted(Counter(y).items()))
print()
print("The first and last columns are containing categorical features:")
print(X[:5])
print()
= SMOTENC(categorical_features=[0, 2], random_state=0)
smote_nc = smote_nc.fit_resample(X, y)
X_resampled, y_resampled print("Dataset after resampling:")
print(sorted(Counter(y_resampled).items()))
print()
print("SMOTE-NC will generate categories for the categorical features:")
print(X_resampled[-5:])
print()
The original imbalanced dataset
[(0, 20), (1, 30)]
The first and last columns are containing categorical features:
[['C' -0.14021849735700803 2]
['A' -0.033193400066544886 2]
['C' -0.7490765234433554 1]
['C' -0.7783820070908942 2]
['A' 0.948842857719016 2]]
Dataset after resampling:
[(0, 30), (1, 30)]
SMOTE-NC will generate categories for the categorical features:
[['A' 0.5246469549655818 2]
['B' -0.3657680728116921 2]
['B' 0.9344237230779993 2]
['B' 0.3710891618824609 2]
['B' 0.3327240726719727 2]]
However, if the dataset is composed of only categorical features then one should use :class:~imblearn.over_sampling.SMOTEN
.
from imblearn.over_sampling import SMOTEN
# Generate only categorical data
= np.array(["A"] * 10 + ["B"] * 20 + ["C"] * 30, dtype=object).reshape(-1, 1)
X = np.array([0] * 20 + [1] * 40, dtype=np.int32)
y
print(f"Original class counts: {Counter(y)}")
print()
print(X[:5])
print()
= SMOTEN(random_state=0)
sampler = sampler.fit_resample(X, y)
X_res, y_res print(f"Class counts after resampling {Counter(y_res)}")
print()
print(X_res[-5:])
print()
Original class counts: Counter({1: 40, 0: 20})
[['A']
['A']
['A']
['A']
['A']]
Class counts after resampling Counter({0: 40, 1: 40})
[['B']
['B']
['A']
['B']
['A']]